import Vue from 'vue'
// import router from '../../router'
import Layout from '@/layout'
import {  constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
// function hasPermission(roles, route) {
//   if (route.meta && route.meta.roles) {
//     return roles.some(role => route.meta.roles.includes(role))
//   } else {
//     return true
//   }
// }

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
// export function filterAsyncRoutes(routes, roles) {
//   const res = []

//   routes.forEach(route => {
//     const tmp = { ...route }
//     if (hasPermission(roles, tmp)) {
//       if (tmp.children) {
//         tmp.children = filterAsyncRoutes(tmp.children, roles)
//       }
//       res.push(tmp)
//     }
//   })

//   return res
// }

const HIDDEN_SIDEBAR_PAGE_NAME = ['createProductInfo', 'editProductInfo','componentModify','badReasonsDetail']

const NO_CACHE_PAGE_NAME = ['createProductInfo']

export function filterRoutes(routers) {
  // 转component字段的字符串为import
  const routerTree = [];
  for (let i = 0; i < routers.length; i++) {
    const {id, name, redirect, path, meta, component, children,WorkStationPermissions} = routers[i];
    const newObj = {
      path,
      redirect,
      name,
      meta: {title: meta.title, icon:meta.icon,WorkStationPermissions}
    };

    //  过滤掉编辑和新增这种类似的页面
    if (HIDDEN_SIDEBAR_PAGE_NAME.includes(newObj.name)){
      newObj.hidden = true
    }

    if (NO_CACHE_PAGE_NAME.includes(newObj.name)){
      newObj.meta.noCache = true
    }

    if (component !== 'Layout') {
      Vue.set(newObj, 'component', () => Promise.resolve(require(`@/views${component}`).default))
      // Vue.set(newObj, 'component', () => import(`../../views${component}`))
      // Vue.set(newObj, 'component', () => import(`@/views${component}`))
    } else {
      Vue.set(newObj, 'component', Layout)
    }
    if (children.length > 0) {
      Vue.set(newObj, 'children', filterRoutes(children))
    }
    routerTree.push(newObj)
  }
  return routerTree
}

export function filterRoutesZ(routers) {
  if (!routers) {
    return
  }
  const routerTree = [];
  for (const router of routers) {
    const newObj = router;
    //  do something that add new attr
    newObj.children = this.filterRoutesZ(router.children);
    routerTree.push(newObj);
  }
  return routerTree;
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, data) {
    return new Promise(resolve => {
      let accessedRoutes=filterRoutes(data)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
